package com.ruiyian.common.utils.jfinsUtil;


import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

/**
 * @author chong
 * @email 673426164@qq.com
 * @create 2021/1/19
 * Desc: 命令生成静态方法
 */
@Slf4j
public class FinsMessageUtils {

    /**
     * 生成读命令信息
     *   位读取
     * @param memoryArea
     * @param registerAddress
     * @param bits
     * @param length
     * @param serverPath
     * @return
     */
    public static FinsMessage createReadFineMessage(int memoryArea, int registerAddress, int bits, int length, String serverPath) {
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress,length,bits,backNodeAddress(serverPath));
        log.info(registerAddress+"发送命令："+finsMessage.toString());
        return finsMessage;
    }

    public static FinsMessage createReadFineMessage(int memoryArea, int registerAddress, int bits, int length, String serverPath,int DEFAULT_SA1_T) {
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress,length,bits,backNodeAddress(serverPath),DEFAULT_SA1_T);
        log.info(registerAddress+"发送命令："+finsMessage.toString());
        return finsMessage;
    }

    /**
     * 生成读命令信息
     *    字读取
     * @param memoryArea
     * @param registerAddress
     * @param length
     * @param serverPath
     * @return
     */
    public static FinsMessage createReadFineMessage(int memoryArea, int registerAddress, int length, String serverPath) {
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress,length,0,backNodeAddress(serverPath));
        log.info(registerAddress+"发送命令："+finsMessage.toString());
        return finsMessage;
    }


    /**
     * 生成读命令信息
     *    字读取
     * @param memoryArea
     * @param registerAddress
     * @param length
     * @param serverPath
     * @return
     */
    public static FinsMessage createReadFineMessage(int memoryArea, int registerAddress, int length, String serverPath,int DEFAULT_SA1_T) {
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress,length,0,backNodeAddress(serverPath),DEFAULT_SA1_T);
        log.info(memoryArea + "/" + registerAddress+"发送命令："+finsMessage.toString());
        return finsMessage;
    }
    /**
     * 写命令    字word写入
     * @param memoryArea
     * @param registerAddress
     * @param pointValue
     * @return
     */
    public static FinsMessage createWriteMessage(Integer memoryArea, Integer registerAddress, Integer pointValue, String serverPath) {
        int[] values = {pointValue};
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress, values,null,backNodeAddress(serverPath));
        return finsMessage;
    }

    /**
     * 按位bits写入操作  02 是D区位代码
     * @param memoryArea
     * @param registerAddress
     * @param bits
     * @param pointValue
     * @return
     */
    public static FinsMessage createWriteMessage(Integer memoryArea, Integer registerAddress, Integer bits, Integer pointValue, String serverPath) {
        int[] values = {pointValue};
        FinsMessage finsMessage = new FinsMessage(memoryArea, registerAddress, bits,values, FinsMessage.ValueType.BCD,backNodeAddress(serverPath));
        return finsMessage;
    }

    public static void main(String[] args) {
        int a = 64;
        System.out.println(String.format("%x", a));
//        FinsMessage writeMessage = FinsMessageUtils.createWriteMessage(49, 0, 0,a,"11.1.1.206:9600");
        FinsMessage writeMessage = FinsMessageUtils.createWriteMessage(130, 211, 0,a,"11.1.1.206:9600");

        FinsMessage readMessage = createReadFineMessage(130, 75, 0,1, "11.1.1.211:9600", 237);
        FinsMessage readMessage2 = createReadFineMessage(130, 75, 0,1, "11.1.1.201:9600", 237);

        System.out.println(readMessage);
        System.out.println(readMessage2);
        //        log.info(writeMessage.toString());
//        log.info(readMessage.toString());
//        System.out.println(readMessage.toString());
//        String a = "{\"type\":\"query\",\n" +
//                "\"tunnelId\":\"24\",\n" +
//                "\"holeId\":\"0\",\n" +
//                "\"moduleId\":9,\n" +
//                "\"groupNum\":0,\n" +
//                "\"equipmentId\":1085,\n" +
//                "\"value\":{\"pointCode\":0,\n" +
//                "    \"eqId\":1085,\n" +
//                "    \"value\":0}}";
//        JSONObject json = JSONObject.fromObject(a);
//        System.out.println(json.get("value").getClass());
    }
    /**
     * 解析命令，返回握手命令还是读命令，写命令
     * @param msg
     * @return
     */
    public static String analysisMessage(Object msg) {
        String str = (String) msg;
        String finsHead = Hex.encodeHexStr(FinsMessage.FINS_HEADER_BYTE,false);
        if(str.contains(finsHead)){
            if (str.length() >= 60) {
                // 取（52,56）的数字并进行转进制，取得是（读命令还是写命令）读命令：0101（257）,写命令 0102（258）
                String str1 = str.substring(52,56);
                int y1= Integer.valueOf(str1,16);
                // 取（56,60）的数字并进行转进制，取得读回来的命令是否成功
                String str2 = str.substring(54,58);
                int y2= Integer.valueOf(str2,16);
                if (y1 == 258) { // 这是写命令
                    if (y2 == 0) { // 代表写命令成功
                        return "writeMessage";
                    }
                    return "writeMessage";
                }
                if (y1 == 257) { // 这是读命令
                    if (y2 == 0) { // 代表读命令成功
                        return "readMessage";
                    }
                    return "readMessage";
                }
            }else {
                if (str.length()==48) {
                    return "handshakeMessage";
                }
            }
        }
        return "";
    }

    /**
     * 截取ip地址最后一个小数点位数据
     * @param serverPath
     * @return
     */
     private static String backNodeAddress(String serverPath){
        if(StringUtils.isNotBlank(serverPath)){
            String substring = serverPath.substring(0, serverPath.indexOf(":"));
            return substring.substring(substring.lastIndexOf(".")+1);
        }
        return "0";
     }
}
